<script setup lang="ts">
import { deleteProcessFileApi, downloadProcessFileApi, getTaskInfoApi, getTaskProcessFileApi } from "@/api/task"
import { TaskProcessFileResData, TaskProcessFileType } from "@/api/task/types/task"
import { Delete, Download } from "@element-plus/icons-vue"
import { ElMessage, ElMessageBox } from "element-plus"
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue"

interface Props {
  id: string | undefined
}
const props = defineProps<Props>()
let timer: number | null = null
const taskId = ref<string | undefined>(props.id)
const loading = ref<boolean>(false)
const activeName = ref<TaskProcessFileType>("model")
const taskStatus = ref<number>(0)
const tabNames = ref<{ name: string; value: TaskProcessFileType }[]>([
  { name: "模型", value: "model" },
  { name: "样本", value: "sample" }
])
const tabNamesMap = computed<{ [propName in TaskProcessFileType]: string }>(() => {
  return tabNames.value.reduce(
    (acc, curr) => {
      acc[curr.value] = curr.name
      return acc
    },
    {} as { [propName in TaskProcessFileType]: string }
  )
})
const tableData = ref<TaskProcessFileResData[]>([])

const getList = () => {
  loading.value = true
  getTaskProcessFileApi(taskId.value as string, activeName.value)
    .then(({ data }) => {
      tableData.value = data
    })
    .catch(() => {
      tableData.value = []
    })
    .finally(() => {
      loading.value = false
    })
}
const handleDelete = (row: TaskProcessFileResData) => {
  ElMessageBox.confirm(`正在删除${tabNamesMap.value[activeName.value]}文件：${row.file_name}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteProcessFileApi(taskId.value as string, row.file_id).then(() => {
      ElMessage.success("删除成功")
      getList()
    })
  })
}
const handleDownload = (row: TaskProcessFileResData) => {
  downloadProcessFileApi(taskId.value as string, row.file_id).then((res) => {
    const blob = new Blob([res.data])
    const contentPosition = res.headers["content-disposition"]
    if (contentPosition) {
      const match = contentPosition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
      const fileName = match[1].replace(/['"]/g, "")
      if ("download" in document.createElement("a")) {
        const elink = document.createElement("a")
        elink.download = fileName
        elink.style.display = "none"
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href)
        document.body.removeChild(elink)
      }
    } else {
      ElMessage.error("下载失败")
    }
  })
}
const getTaskInfo = () => {
  taskId.value &&
    getTaskInfoApi(taskId.value).then(({ data }) => {
      taskStatus.value = data.task_status
    })
}

watch(
  () => activeName.value,
  () => {
    getList()
  }
)

onMounted(() => {
  getTaskInfo()
  getList()
  timer = Number(
    setInterval(() => {
      if (taskStatus.value == 1) {
        getTaskInfo()
        getList()
      }
    }, 1000 * 60)
  )
})
onBeforeUnmount(() => {
  timer && clearInterval(timer)
})
</script>
<template>
  <el-tabs v-model="activeName" class="demo-tabs" stretch>
    <el-tab-pane v-for="item in tabNames" :label="item.name" :name="item.value" :key="item.value">
      <el-table :data="tableData" style="width: 100%" border>
        <el-table-column type="index" label="序号" width="120" align="center" />
        <el-table-column prop="file_name" label="名称" />
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="{ row }">
            <el-button link type="primary" size="large" :icon="Delete" @click="handleDelete(row)"> 删除 </el-button>
            <el-button link type="primary" size="large" :icon="Download" v-throttle="() => handleDownload(row)"
              >下载</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>
  </el-tabs>
</template>
